//导入 jwt
const jwt = require('jsonwebtoken');
//读取配置项
const { secret } = require('../config/config');
//声明中间件
module.exports = async (ctx, next) => {
  //获取 token
  if ((ctx.url.split('?')[0]) == '/login') {
    await next()
  } else {
    let token = ctx.req.headers.authorization
    if (token) {
      const tokenItem = jwt.verify(token, secret)
      const { time, timeout } = tokenItem
      let Newtime = new Date().getTime()
      if (Newtime - time <= timeout) {
        await next()
      } else {
        ctx.body = {
          status: 405,
          message: 'token已过期,请重新登录'
        }
      }
    }
    else {
      ctx.body = {
        status: 405,
        message: '请带上token'
      }
    }
  }
}